<template>
  <view class="wrong-container">
    <hi-navbar
      fixed
      back
      transparent="show"
      :backgroundColor="[237, 240, 243]"
      title="我的错题"
    >
    </hi-navbar>

    <div v-if="list.length !== 0">
      <!-- 试卷列表 -->
      <question-list
        :question-list="list"
        :can-select="false"
        :is-show-answer="true"
        :is-show-close="true"
        :is-show-footer="true"
        @collect="onCollect"
        @answer="onAnswer"
        @close="onClose"
      ></question-list>
    </div>
    <image
      src="/static/image/home/empty.jpg"
      mode="widthFix"
      v-else
      class="emptyimg"
    ></image>
  </view>
</template>

<script>
import QuestionList from "_c/Question/QuestionList"
import { mapActions } from "vuex"
import func from "_u/func"

export default {
  components: {
    QuestionList,
  },
  data() {
    return {
      list: [],
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    //  初始化数据
    async init() {
      uni.showLoading()
      let wrongQuestionRes = await this.getWrongQuestions()
      wrongQuestionRes = wrongQuestionRes.data.objects
      console.log("init -> wrongQuestionRes", wrongQuestionRes)

      let _wronglist = []
      this.list = wrongQuestionRes
        .filter((item) => {
          if (_wronglist.includes(item.question.id)) {
            return false
          } else {
            _wronglist.push(item.question.id)
            return true
          }
        })
        .map((item) => {
          let answerIntro = ""
          const format = (item) => {
            let { selectOption, type, isWrong, right } = item
            let val = isWrong ? selectOption : +right
            if (+val == -8 || val == undefined) {
              return "未选择任何选项"
            } else if (type === "多选") {
              const letter = item.right
                .split(",")
                .map((item) => {
                  return { 1: "A", 2: "B", 3: "C", 4: "D" }[item]
                })
                .join(", ")
              return `你的选择是: ${letter}`
            } else if (type === "单选") {
              const letter = { 1: "A", 2: "B", 3: "C", 4: "D" }[val]
              return `你的选择是: ${letter}`
            } else if (type === "判断") {
              const letter = { 1: "对", 2: "不对" }[val]
              return `你的选择是: ${letter}`
            }
          }
          answerIntro = format(item.question)
          return Object.assign(
            {
              answerIntro,
              paperId: item.paper.id,
              wrongId: item.id,
              paperTitle: item.paper.title,
              paperCreateAt: item.created_at,
              isCollected: item.isCollected,
            },
            item.question
          )
        })
      uni.hideLoading()
      console.log("init -> this.list", this.list)
    },

    // 获取错误问题
    async getWrongQuestions() {
      let QuestionErrer = new wx.BaaS.TableObject("question_error")
      return QuestionErrer.expand(["question", "paper"]).limit(1000).find()
    },

    async onCollect(questionIndex) {
      const selectItem = this.list[questionIndex]
      let QuestionWrong = new wx.BaaS.TableObject("question_error")

      // 取消收藏
      if (selectItem.isCollected) {
        uni.showLoading()

        let recordID = selectItem.wrongId // 数据行 id

        let Wrong = new wx.BaaS.TableObject("question_error")
        let wrongItem = Wrong.getWithoutData(recordID)

        wrongItem.set("isCollected", false)
        await wrongItem.update()

        // 删除保存的收藏记录
        let Collect = new wx.BaaS.TableObject("question_collect")
        let Question = new wx.BaaS.TableObject("question")
        let query = new wx.BaaS.Query()

        query.compare("question", "=", Question.getWithoutData(selectItem.id))
        await Collect.limit(10).offset(0).delete(query)

        this.list[questionIndex]["isCollected"] = false
        uni.showToast({ title: "已取消收藏!", icon: "none" })
      } else {
        // 收藏
        uni.showLoading()
        let recordID = selectItem.wrongId // 数据行 id

        let Wrong = new wx.BaaS.TableObject("question_error")
        let wrongItem = Wrong.getWithoutData(recordID)

        wrongItem.set("isCollected", true)
        await wrongItem.update()

        let QuestionPaper = new wx.BaaS.TableObject("question_paper")
        let Question = new wx.BaaS.TableObject("question")
        let Collect = new wx.BaaS.TableObject("question_collect")
        let MyRecord = Collect.create()
        MyRecord.set({
          paper: QuestionPaper.getWithoutData(selectItem.paperId),
          question: Question.getWithoutData(selectItem.id),
        })
        await MyRecord.save()

        this.list[questionIndex]["isCollected"] = true

        uni.showToast({ title: "收藏成功!" })
      }
    },

    onAnswer(index) {
      const selectItem = this.list[index]
      this.$set(this.list, index, {
        ...selectItem,
        isShowAnswer: !selectItem.isShowAnswer,
      })
    },

    async onClose(index) {
      const selectItem = this.list[index]

      const QuestionWrong = new wx.BaaS.TableObject("question_error")
      let Question = new wx.BaaS.TableObject("question")

      let query = new wx.BaaS.Query()
      query.compare("question", "=", Question.getWithoutData(selectItem.id))

      await QuestionWrong.limit(10).offset(0).delete(query)
      this.list.splice(index, 1)
      uni.showToast({ title: "已删除!", icon: "none" })
    },
  },
}
</script>

<style lang="scss" scope>
.header-wrap {
  &__item {
    background: #ecf0f3;

    box-shadow: 13px 13px 21px #c2c2c6, -13px -13px 21px #fff;
  }
}
.emptyimg {
  position: absolute;
  bottom: 0;
  left: 0;

  width: 100%;
}
</style>
